package light.head.controller.sys;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.cache.Cache;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.OrganTypeHandleDAO;
import light.head.dao.sys.RoleDAO;
import light.head.dao.sys.RoleHandleDAO;
import light.head.dao.sys.RoleMainDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.entity.SystemInfo;
import light.head.model.Role;
import light.head.model.RoleHandle;
import light.head.model.RoleMain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author janhang
 * @2011-8-22  下午03:10:04
 * 权限管理
 */
@Controller
@RequestMapping(value = Url.C_ROLE)
public class RoleController extends SupporterController {

	private RoleDAO roleDAO;
	private RoleMainDAO rmDAO;
	private RoleHandleDAO rhDAO;
	private OrganTypeHandleDAO othDAO;
	private OrganDAO organDAO;


	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.ROLE_INIT);
	}

	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.CU);
		List<Integer> sonList = organDAO.getSonCodeList(organDAO.getRoot(cu_organCode(request)).getCode());
		if(null == sonList || sonList.size() < 0 ){
			
		}else{
			String soncs = Arrays.toString(sonList.toArray());
			map.put(Parm.SON_LIST, soncs);
		}
		if (roleDAO.findByMap(organDAO.getRoot(cu_organCode(request)).getCode(), map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.ROLE_LIST);
	}
	/**
	 * 删除角色权限
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.ERROR);
			return;
		}
		
		Role role = roleDAO.get(Integer.parseInt(code));
		if (null == role)
			print(response, Msg.NOT_FIND);
		else {
			role.setDeleted(true);
			if(RESULT.SUCCESS == roleDAO.upd(role)) {
				roleDAO.loadAllByOrgCode(cu_organCode(request));
				print(response, Msg.SUCCESS);
			}
		}
	}
	
	/**
	 * 删除角色
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = Url.DELETEROLE)	
	public void deleteByCode(Integer code, HttpServletRequest request, HttpServletResponse response){
		if(null == code || code < 0){
			print(response, Msg.NOT_FIND);			
		}else{
			roleDAO.del(code);
		}
		
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		Map<String, Boolean> map = null;
		String url = Url.ROLE_EDIT;
		if (isNotNull(code)) {
			Role role = roleDAO.get(Integer.parseInt(code));
			map = rmDAO.findToMap(role.getCode());
			request.setAttribute(Parm.ROLE, role);
			url = Url.ROLE_EDITSHOW;
		}/*else{
			Organ o = organDAO.get(cu_organCode(request));
			request.setAttribute(Parm.OC, o.getCode());
			request.setAttribute(Parm.OCN, o.getName());
		}*/
		
		// 该处理因为freemarker不能处理空值，
		if (null == map)
			map = new HashMap<String, Boolean>();
		
		request.setAttribute(Parm.MAP, map);
		return new ModelAndView(url);
	}
	
	

	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(Role role, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null == role) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		Integer cu_organCode = organDAO.getRoot(cu_organCode(request)).getCode();		// 角色都属于根机构,
		
		if (role.getIsDefault())
			roleDAO.updateDefaultRole(cu_organCode);

		RESULT result = RESULT.ERROR;
		if (null == role.getCode()) {
			List<Role> r = roleDAO.findByOrganCode((organDAO.getRoot(cu_organCode)).getCode().toString());
			for (Role ro : r) {
				if(ro.getName().equals(role.getName())) {
					print(response, Msg.NAME_SAME);
					return;
				}
			}
			System.out.println();
			role.setCt(new Date());
			role.setDeleted(false);
			role.setCu(cu_code(request));
			role.setOc((organDAO.getRoot(cu_organCode)).getCode());
			result = roleDAO.add(role);
		} else {
			result = roleDAO.update(role);
		}
		if (RESULT.SUCCESS == result) {
			rmDAO.delByRoleCode(role.getCode());
			String[] list = request.getParameterValues(Parm.TC);
			if (null != list && list.length > 0) {
				RoleMain rm = null;
				for (String tc : list) {
					if (isNotNull(tc)) {
						rm = new RoleMain();
						rm.setRc(role.getCode());
						rm.setTc(Short.parseShort(tc));
						rmDAO.add(rm);
					}
				}
			}
			roleDAO.loadAllByOrgCode(cu_organCode);
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}

	@RequestMapping(value = Url.EDIT_HANDLE)
	public ModelAndView editHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
		} else {
			Map<String, Boolean> map = rhDAO.getHandleMapByRoleCode(Integer.parseInt(code));
			Map<String, Boolean> orgMap = othDAO.getHandleMapByOrganTypeCode(cu_organTypeCode(request));
//			List<Module> menu = Cache.moduleList;
			List<SystemInfo> systemInfoList = Cache.systemInfoList;
			request.setAttribute(Parm.HANDLE_MAP, map);
			request.setAttribute(Parm.ORG_HANDLE_MAP, orgMap);//当前机构类型对应的所有操作
			request.setAttribute(Parm.MENU, systemInfoList);
		}
		request.setAttribute(Parm.CODE, code);
		
		
		return new ModelAndView(Url.ROLE_EDIT_HANDLE);
	}

	@RequestMapping(value = Url.SAVE_HANDLE)
	@Transactional
	public void saveHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		String handleStr = request.getParameter("handleList");
		
		if (null == code || null == handleStr) {
			print(response, Msg.ERROR);
		} else {
			Integer c = Integer.parseInt(code);
			if (rhDAO.deleteByRoleCode(c) == RESULT.SUCCESS) {
				String[] list = handleStr.split(Sys.COMMA);
				if (null != list && list.length > 0) {
					for (String hcode : list) {
						if (isNotNull(hcode)) {
							RoleHandle rh = new RoleHandle();
							rh.setRoleCode(c);
							rh.setHandleCode(hcode);
							
							rhDAO.add(rh);
						}
					}
				}
				Cache.roleMap.put(c, rhDAO.loadHandleMapByRoleCode(c));
				print(response, Msg.SUCCESS);
			} else 
				print(response, Msg.ERROR);
		}
	}
	
	
	@Autowired
	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	@Autowired
	public void setRhDAO(RoleHandleDAO rhDAO) {
		this.rhDAO = rhDAO;
	}
	@Autowired
	public void setOthDAO(OrganTypeHandleDAO othDAO) {
		this.othDAO = othDAO;
	}
	@Autowired
	public void setRmDAO(RoleMainDAO rmDAO) {
		this.rmDAO = rmDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
}
